import React, { Suspense } from "react";
import { Switch, Route, Redirect } from "react-router-dom";
function RoutesViews(props) {
  // var roles = localStorage.getItem('userInfo')&&JSON.parse(localStorage.getItem('userInfo')).role.permissions
  //解构
  var { routes } = props;

  //过滤普通路由表
  var normalRoutes = routes.filter((item) => {
    // return item.path && item.component && !item.rolenum || item.path && item.component && roles&&roles.some(item1=> item1==item.rolenum )
    return item.path && item.component;
  });

  //过滤重定向路由表
  var redirectRoutes =
    routes &&
    routes.filter((item) => {
      return item.from && item.to;
    });
  //过滤404路由
  var notFoundRoutes = routes.filter((item) => {
    return !item.path && item.component;
  });
  return (
    <Suspense fallback={<></>}>
      <Switch>
        {/* 渲染普通路由 */}
        {normalRoutes.map((item, index) => {
          return (
            <Route
              exact={item.exact}
              key={index}
              path={item.path}
              render={(props) => {
                if (item.children && item.children.length > 0) {
                  return (
                    <item.component
                      {...props}
                      routes={item.children}
                    ></item.component>
                  );
                } else {
                  return <item.component {...props}></item.component>;
                }
              }}
            ></Route>
          );
        })}

        {/* 重定向路由渲染 */}
        {redirectRoutes.map((item, index) => {
          return (
            <Redirect
              exact={item.exact}
              key={index}
              from={item.from}
              to={item.to}
            ></Redirect>
          );
        })}

        {/* 404路由的渲染 */}
        {notFoundRoutes.map((item, index) => {
          return <Route key={index} component={item.component}></Route>;
        })}
      </Switch>
    </Suspense>
  );
}

export default RoutesViews;
